<script setup>
// 市场占有率分析
import { ref, onMounted } from 'vue'

const chartOption = ref({
	backgroundColor: 'transparent', // 透明背景以适配深色主题
	tooltip: {
		trigger: 'axis',
		axisPointer: {
			type: 'cross',
			label: {
				backgroundColor: '#6a7985',
			},
		},
		valueFormatter: function (value) {
			return value + '%'
		},
	},
	legend: {
		top: '10%',
		data: [],
	},
	grid: {
		top: '15%',
		left: '4%',
		right: '4%',
		bottom: '10%',
		containLabel: true,
	},
	xAxis: {
		type: 'category',
		boundaryGap: false,
		data: [],
	},
	yAxis: {
		type: 'value',
		axisLabel: {
			formatter: '{value}%',
		},
		//刻度设置为5个
		splitNumber: 3,
	},
	series: [],
})

onMounted(async () => {
	try {
		const response = await fetch('http://localhost/api/ads-market-share')
		if (!response.ok) {
			throw new Error(`HTTP error! status: ${response.status}`)
		}
		const apiData = await response.json()

		// 处理API数据
		const dates = [...new Set(apiData.map(item => item.statisticDate))].sort()
		const brands = [...new Set(apiData.map(item => item.competitorBrand))]

		const series = brands.map(brand => {
			const data = dates.map(date => {
				const item = apiData.find(i => i.competitorBrand === brand && i.statisticDate === date)
				return item ? item.marketShare : 0
			})
			return {
				name: brand,
				type: 'line',
				stack: 'total',
				lineStyle: { type: 'solid' },
				areaStyle: {},
				emphasis: { focus: 'series' },
				data,
			}
		})

		// 更新图表配置
		chartOption.value.xAxis.data = dates
		chartOption.value.series = series
		chartOption.value.legend.data = brands
	} catch (error) {
		console.error('获取市场占有率数据失败:', error)
	}
})
</script>

<template>
	<v-chart theme="chalk" :option="chartOption" />
</template>

<style scoped></style>
